//
//  EFengShareCommentToolBar.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/3/11.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFengShareCommentToolBar.h"
#import "MBProgressHUD+WZ.h"
#import "EFengShareEmotionView.h"


#define ChatToolPosY  64.0f
#define EmotionPosY    64.0f
#define EmotionHeight  180.0f
#define MoreHeight 150.0f
#define EdgeSpaceLeft   (HARDWARE_SCREEN_WIDTH-300)/2
#define shareMaxTextCount 100

#define MaxLines 13
#define MaxHeight 16+MaxLines*22

static EFengShareCommentToolBar* shared;

@interface EFengShareCommentToolBar ()<EFengShareEmotionViewDelegate>

AssignProperty CGFloat proToolHeight;


@end

@implementation EFengShareCommentToolBar

+(EFengShareCommentToolBar *)defaultShareCommentToolBar
{
    @synchronized(self)
    {
        if(shared == nil)
        {
            shared = [[EFengShareCommentToolBar alloc] init];
        }
    }
    return shared;
}


- (id)init
{
    self = [super init];
    if (self) {
        
        self.backgroundColor = RGBCOLOR(226, 226, 226);
        self.frame = CGRectMake(0,HARDWARE_SCREEN_HEIGHT - 64, HARDWARE_SCREEN_WIDTH, 50);
        self.isEmotionShow = YES;
        [self setDesign];
        [self loadNotifications];
    }
    return self;
}

-(void)setDesign
{
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, 0.5f)];
    line.backgroundColor = RGBCOLOR(212, 212, 212);
    [self addSubview:line];
    
    _emotionBtn = [self buttonWithFrame:CGRectMake(HARDWARE_SCREEN_WIDTH - 39.0f, 0.0f, 39.0f, 50.0f) normalImg:@"chatviewtool_expression.png" selectedImg:@"chatviewtool_expression.png" tag:101 action:@selector(emotionBtnMethod:)];
    [self addSubview:_emotionBtn];

    
    _contentText = [[UIExpandingTextView alloc] initWithFrame:CGRectMake(10.0f, 6.0f, _emotionBtn.frame.origin.x - 10.0f, 44.0f)];
    [_contentText setDelegate:self];
    [_contentText setReturnKeyType:UIReturnKeySend];
    [_contentText setMaximumNumberOfLines:4];
    //    [_contentText setAnimateHeightChange:YES];
    [self addSubview:_contentText];
    
    CGRect bgfra = _contentText.frame;
    bgfra.size.height -= 6;
    

    
    
    [EFengShareEmotionView defaultShareEmotionView].EFengShareEmotionViewDelegate = self;
}

- (ISTThemeButton *)buttonWithFrame:(CGRect)frame normalImg:(NSString*)normalImg selectedImg:(NSString*)selectedImg tag:(int)tagValue action:(SEL)sel
{
    ISTThemeButton *btn = [[ISTThemeButton alloc] initWithFrame:CGRectZero];
    [btn setFrame:frame];
    [btn setImageStr:normalImg forState:UIControlStateNormal];
    [btn setImageStr:selectedImg forState:UIControlStateSelected];
    [btn setImageStr:selectedImg forState:UIControlStateHighlighted];
    
    [btn setTag:tagValue];
    [btn addTarget:nil action:sel forControlEvents:UIControlEventTouchUpInside];
    return btn;
}

- (ISTThemeButton *)buttonWithFrame:(CGRect)frame normalImg:(NSString*)normalImg selectedImg:(NSString*)selectedImg text:(NSString*)text tag:(int)tagValue action:(SEL)sel
{
    ISTThemeButton *btn = [[ISTThemeButton alloc] initWithFrame:CGRectZero];
    [btn setFrame:frame];
    [btn setBackgroundImageStr:normalImg forState:UIControlStateNormal];
    [btn setTitle:text forState:UIControlStateNormal];
    // [btn setBackgroundImage:selectedImg forState:UIControlStateSelected];
    [btn setTag:tagValue];
    [btn addTarget:nil action:sel forControlEvents:UIControlEventTouchUpInside];
    return btn;
}


- (void)eFengShareEmotionViewViewDidSend
{
    [self sendBtnMethod:nil];
}


#pragma mark- uiexpandtextviewdelegate

-(BOOL)expandingTextView:(UIExpandingTextView *)expandingTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    [expandingTextView.internalTextView setSelectedRange:range];
    return YES;
}
-(BOOL)expandingTextViewShouldBeginEditing:(UIExpandingTextView *)expandingTextView
{
    return YES;
}
- (BOOL)expandingTextViewShouldReturn:(UIExpandingTextView *)expandingTextView
{
    [self sendBtnMethod:nil];
    return YES;
}
- (void)expandingTextViewDidBeginEditing:(UIExpandingTextView *)expandingTextView{
   
    
    if (!self.isEmotionShow) {
        self.textSelectRange = NSMakeRange(0, 0);
        
        EFengShareEmotionView* emo = [EFengShareEmotionView defaultShareEmotionView];
        CGRect emoFrame = emo.frame;
        emoFrame.origin.y = HARDWARE_SCREEN_HEIGHT - EmotionPosY;
        
        [emo setFrame:emoFrame];
        self.isEmotionShow = !self.isEmotionShow;
    }
    
    
}

-(void)expandingTextViewDidEndEditing:(UIExpandingTextView *)expandingTextView{
    
    
}

- (void)expandingTextViewDidChange:(UIExpandingTextView *)expandingTextView
{
    if (![self checkTextCount:expandingTextView.text])
    {
        [MBProgressHUD showSuccess:[NSString stringWithFormat:@"发送的文本不能超过%zd字",shareMaxTextCount]];
        
        expandingTextView.text = [expandingTextView.text substringToIndex:shareMaxTextCount];
        
    }
    [expandingTextView scrollRangeToVisible:expandingTextView.selectedRange];
    
}

- (BOOL)checkTextCount:(NSString *)text
{
    NSInteger length = text.length;
    if (length > shareMaxTextCount) {
        return NO;
    }
    return YES;
}



- (void)contentTextViewTextDidChangeWithText:(NSString *)text
{
    
}
- (void)expandingTextView:(UIExpandingTextView *)expandingTextView willChangeHeight:(float)height
{
    
    //    CGRect fra = _contentText.frame;
    //    fra.size.width =  HARDWARE_SCREEN_WIDTH - (_voiceChangeBtn.frame.origin.x+_voiceChangeBtn.frame.size.width) - 78;
    //    [_contentText setFrame:fra];
    //    CGFloat hei = expandingTextView.frame.size.height;
    //    if (!isEmotionShow) {
    //        if (height>38&&height<=MaxHeight) {
    //            CGRect frame = self.frame;
    //            frame.origin.y = HARDWARE_SCREEN_HEIGHT-70-hei-EmotionHeight;
    //            frame.size.height = hei+6;
    //            [self setFrame:frame];
    //            frame.origin.x = 0;
    //            frame.origin.y = 0;
    //            [_imageView setFrame:frame];
    //
    //            _contentText.internalTextView.contentOffset=CGPointMake(0,_contentText.internalTextView.contentSize.height-_contentText.internalTextView.frame.size.height);
    //        }
    //    }
}
- (void)expandingTextView:(UIExpandingTextView *)expandingTextView didChangeHeight:(float)height
{
    if (!_contentText.internalTextView.isFirstResponder && expandingTextView.text.length <= 0 && self.isEmotionShow) {
        return;
    }
    CGFloat hei = expandingTextView.frame.size.height;
    
    if ( hei>44 && hei <= MaxHeight) {
        CGRect frame = self.frame;
        if (!self.isEmotionShow) {
            frame.origin.y = HARDWARE_SCREEN_HEIGHT-70-hei-EmotionHeight;
            frame.size.height = hei + 6;
        }else
        {
            frame.origin.y = HARDWARE_SCREEN_HEIGHT-70-hei-_KeyBoardHeight;
            frame.size.height = hei+6;
        }
        [self setFrame:frame];
        
    } else if (hei<=44) {
        
        CGRect frame = self.frame;
        if (!self.isEmotionShow) {
            frame.origin.y = HARDWARE_SCREEN_HEIGHT-70-hei-EmotionHeight;
        }else {
            frame.origin.y = HARDWARE_SCREEN_HEIGHT-70-hei-_KeyBoardHeight;
        }
        frame.size.height = hei+6;
        [self setFrame:frame];
    }
    
    
    
}

- (void)emotionBtnMethod:(id)sender
{
    if (_contentText.internalTextView.isFirstResponder) {
        [_contentText.internalTextView resignFirstResponder];
    }
    
    [self emoViewShow];
}

-(void)emoViewShow
{
    EFengShareEmotionView *emo = [EFengShareEmotionView defaultShareEmotionView];
    if (!self.isEmotionShow) {       //消失
       
        
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.25f];
        [UIView setAnimationCurve:7];
        [UIView setAnimationBeginsFromCurrentState:YES];
        
        CGRect emoFrame = emo.frame;
        emoFrame.origin.y = HARDWARE_SCREEN_HEIGHT - EmotionPosY;
        
        
        
        CGRect frame = self.frame;
        frame.origin.y = HARDWARE_SCREEN_HEIGHT -64.0f;
        [self setFrame:frame];
        [emo setFrame:emoFrame];
        
        [UIView commitAnimations];
        
        if (self.eFengShareCommentToolBarDelegate != nil && [self.eFengShareCommentToolBarDelegate respondsToSelector:@selector(EFengShareCommentToolBarDidHiddenEmotionBtn)]) {
            [self.eFengShareCommentToolBarDelegate EFengShareCommentToolBarDidHiddenEmotionBtn];
        }
    }
    else            //出现
    {
        _proToolHeight = _contentText.frame.size.height;
        //        [_sendBtn setHidden:NO];
        
        CGRect emoFrame = emo.frame;
        emoFrame.origin.y = HARDWARE_SCREEN_HEIGHT - EmotionHeight - EmotionPosY;
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.25f];
        [UIView setAnimationCurve:7];
        [UIView setAnimationBeginsFromCurrentState:YES];
        
        
        CGRect frame = self.frame;
        frame.origin.y = HARDWARE_SCREEN_HEIGHT-64-_proToolHeight - 6 - EmotionHeight;
        frame.size.height = _proToolHeight + 6;
        [self setFrame:frame];
        [emo setFrame:emoFrame];
        
        
        [UIView commitAnimations];
        
    }
    self.isEmotionShow = !self.isEmotionShow;
}

- (void)sendBtnMethod:(id)sender
{
    
    if(self.eFengShareCommentToolBarDelegate != nil && [self.eFengShareCommentToolBarDelegate respondsToSelector:@selector(sendMsg:)])
    {
        [self.eFengShareCommentToolBarDelegate sendMsg:_contentText.internalTextView.text];
    }
    _contentText.text = @"";
    
    [self setNewFrameOfTool1];
    
}

-(void)setNewFrameOfTool1
{
    _proToolHeight = 44;
    
    CGRect fra =self.frame;
    fra.origin.y = HARDWARE_SCREEN_HEIGHT-64.0f;
    fra.size.height = 6+_proToolHeight;
    [self setFrame:fra];
    [_contentText textViewDidChange:_contentText.internalTextView];
}


-(void)setOriginFrameOfTool
{
    _proToolHeight = 44;
    CGRect fra =self.frame;
    fra.origin.y = HARDWARE_SCREEN_HEIGHT - 64.0f;
    fra.size.height = 6+_proToolHeight;
    [self setFrame:fra];
}

-(void)setNewFrameOfTool
{
    if (_proToolHeight ==0) {
        _proToolHeight = 44;
    }
    CGRect fra =self.frame;
    fra.origin.y = HARDWARE_SCREEN_HEIGHT-64.0f;
    fra.size.height = 6+_proToolHeight;
    [self setFrame:fra];
    [_contentText textViewDidChange:_contentText.internalTextView];
}


-(void)addEmotionStr:(NSNotification *)notification
{
    NSString *str = (NSString*)notification.object;
    if (!_contentText.internalTextView.text) {
        _contentText.internalTextView.text = @"";
    }
    
    NSRange tempRange = [_contentText.internalTextView selectedRange];
    if (self.textSelectRange.location < [_contentText.internalTextView selectedRange].location&&self.textSelectRange.location!=0) {
        tempRange = self.textSelectRange;
    }
    
    NSString *firstStr = [_contentText.internalTextView.text substringToIndex:tempRange.location];
    NSString *lastStr =[_contentText.internalTextView.text substringFromIndex:tempRange.location];
    
    NSString *new_str = [NSString stringWithFormat:@"%@%@%@",firstStr,str,lastStr];
    NSRange range = NSMakeRange([[NSString stringWithFormat:@"%@%@",firstStr,str] length], 1);
    self.textSelectRange = range;
    
    [_contentText.internalTextView setText:new_str];
    [_contentText textViewDidChange:_contentText.internalTextView];
    
}


- (void)deleteEmotionStr{
    if ([_contentText.internalTextView.text length]>2) {
        NSMutableString *str =[NSMutableString stringWithString:_contentText.internalTextView.text];
        if ([[str substringFromIndex:[str length]-1] isEqualToString:@"]"]) {
            [str deleteCharactersInRange:NSMakeRange([str length]-1, 1)];
            for (int index=0; index<[_contentText.internalTextView.text length]-1; index++) {
                if (![[str substringFromIndex:[str length]-1] isEqualToString:@"["]) {
                    if ([[str substringFromIndex:[str length]-1] isEqualToString:@"]"]) {
                        break;
                    }
                    [str deleteCharactersInRange:NSMakeRange([str length]-1, 1)];
                }else {
                    [str deleteCharactersInRange:NSMakeRange([str length]-1, 1)];
                    [_contentText.internalTextView setText:str];
                    [_contentText textViewDidChange:_contentText.internalTextView];
                    break;
                }
                
            }
            
        }
    }
}
- (void)resetToolPositionToInitial
{
    _proToolHeight = self.contentText.height;
    if (!self.isEmotionShow) {
        
        EFengShareEmotionView* emo = [EFengShareEmotionView defaultShareEmotionView];
        CGRect emoFrame = emo.frame;
        emoFrame.origin.y = HARDWARE_SCREEN_HEIGHT - EmotionPosY;
        [emo setFrame:emoFrame];
        self.isEmotionShow = YES;
        
    }
    

    [_contentText.internalTextView resignFirstResponder];
    _contentText.placeholder = @"";
    
    
    CGRect fra =self.frame;
    fra.origin.y = HARDWARE_SCREEN_HEIGHT - 64.0f;
    fra.size.height = 6 + _proToolHeight;
    [self setFrame:fra];
    
}

-(void)reSetChatTool
{
    //more,emo,key,ziji
    
    if (_proToolHeight == 0) {
        _proToolHeight = 44;
    }
    
    
    
    if (!self.isEmotionShow) {
        EFengShareEmotionView* emo = [EFengShareEmotionView defaultShareEmotionView];
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.25f];
        [UIView setAnimationCurve:7];
        [UIView setAnimationBeginsFromCurrentState:YES];
        
        CGRect emoFrame = emo.frame;
        emoFrame.origin.y = HARDWARE_SCREEN_HEIGHT - EmotionPosY;
        [emo setFrame:emoFrame];
        self.isEmotionShow = YES;
        
        
        CGRect fra =self.frame;
        fra.origin.y = HARDWARE_SCREEN_HEIGHT - 64.0f;
        fra.size.height = 6+_proToolHeight;
        [self setFrame:fra];
        
        
        [UIView commitAnimations];
        
    } else if ([_contentText.internalTextView isFirstResponder]) {
        [_contentText.internalTextView resignFirstResponder];
        
    }
    
    
    
    
    
}

-(void)dealloc
{
    //    NSLog(@"ChatToolBar dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:shareSendTagOfEmotionIcon object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:EFengShareCommentToolBarMoved object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:shareDeleteTagOfEmotionIcon object:nil];
}

#pragma mark-
#pragma mark --通知及其回调方法--

- (void)keyboardWillShow:(NSNotification *)notification
{
    
    NSDictionary *keyboardInfo = [notification userInfo];
    UIViewAnimationCurve animationCurve;
    [[keyboardInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    NSValue *aValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [aValue CGRectValue];
    
    _KeyBoardHeight = keyboardFrame.size.height;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.25f];
    [UIView setAnimationCurve:animationCurve];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    
    CGRect frame = self.frame;
    
    frame.origin.y = HARDWARE_SCREEN_HEIGHT - keyboardFrame.size.height - self.frame.size.height - 64;
    _proToolHeight = self.frame.size.height - 6;
    [self setFrame:frame];
    [UIView commitAnimations];
}

- (void)keyboardWillhide:(NSNotification *)notification
{
    NSDictionary *keyboardInfo = [notification userInfo];
    UIViewAnimationCurve animationCurve;
    [[keyboardInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:[[keyboardInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
    [UIView setAnimationCurve:animationCurve];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    CGRect frame = self.frame;
    frame.origin.y = HARDWARE_SCREEN_HEIGHT - 64;
    [self setFrame:frame];
    
    [UIView commitAnimations];
}

- (void)loadNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addEmotionStr:) name:shareSendTagOfEmotionIcon object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillhide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteEmotionStr) name:shareDeleteTagOfEmotionIcon object:nil];
    
}

@end
